package com.cen.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author : cen
 * @date : 2020/5/15 19:18
 */
public class BaseDao {
    private  static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        Properties properties = new Properties();
        InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("database.properties");
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }


    public static Connection getConnection(){
           Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    /*查询公共*/
    public static ResultSet excute(Connection connection, PreparedStatement pstm, ResultSet resultSet, String sql, Object []param) throws SQLException {
         pstm = connection.prepareStatement(sql);
         for (int i=0;i<param.length;i++){
            pstm.setObject(i+1,param[i]);
         }
         resultSet = pstm.executeQuery();
         return resultSet;
    }
    /*增删改*/
    public static int excuteUpdate(Connection connection, PreparedStatement pstm,String sql, Object []paream ) throws SQLException {
        pstm = connection.prepareStatement(sql);
        for (int i=0;i<paream.length;i++){
            pstm.setObject(i+1,paream[i]);
        }
        int i = pstm.executeUpdate(sql);
        return i;
    }
    public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet resultSet){
        boolean flag = true;
        if (resultSet != null){
            try {
                resultSet.close();
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
           flag = false;

        }
        if (pstm != null){
            try {
                pstm.close();
                pstm = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
            flag = false;

        }
        if (resultSet != null){
            try {
                resultSet.close();
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
            flag = false;

        }
    return flag;
    }
}
